package cn.taoticket.service.impl;

import cn.taoticket.client.RestTaoticketImageClient;
import cn.taoticket.client.RestTaoticketLinkUserClient;
import cn.taoticket.client.RestTaoticketUserClient;
import cn.taoticket.common.Constants;
import cn.taoticket.common.EmptyUtils;
import cn.taoticket.common.RedisUtils;
import cn.taoticket.pojo.TaoticketImage;
import cn.taoticket.pojo.TaoticketLinkUser;
import cn.taoticket.pojo.TaoticketUser;
import cn.taoticket.service.TaoTicketUserService;
import cn.taoticket.vo.QueryLinkUserVo;
import cn.taoticket.vo.TTUserVO;
import cn.taoticket.vo.TokenVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
public class TaoTicketUserServiceImpl implements TaoTicketUserService {
    @Resource
    private RestTaoticketUserClient restTaoticketUserClient;
    @Resource
    private RestTaoticketImageClient restTaoticketImageClient;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RestTaoticketLinkUserClient restTaoticketLinkUserClient;

    @Override
    public Object[] login(TaoticketUser taoticketUser) throws Exception {
        //验证用户登录是否成功
        TaoticketUser hasTaoticketUser = restTaoticketUserClient.checkLoginByPassword(taoticketUser);
        if (EmptyUtils.isEmpty(hasTaoticketUser)) {
            return null;
        }
        //组装信息
        TTUserVO ttUserVO = new TTUserVO();
        BeanUtils.copyProperties(hasTaoticketUser, ttUserVO);
        ttUserVO.setUserId(hasTaoticketUser.getId());
        //更新用户头像，需要调用查找图片的服务
        List<TaoticketImage> userImages = restTaoticketImageClient.queryImageList(hasTaoticketUser.getId(), Constants.Image.ImageType.normal, Constants.Image.ImageCategory.user);
        //如果不为null,组装图片信息
        if (EmptyUtils.isNotEmpty(userImages)) {
            ttUserVO.setImageId(userImages.get(0).getId());
            ttUserVO.setImgUrl(userImages.get(0).getImgUrl());
        } else {
            //如果为null，则显示默认图片
            ttUserVO.setImgUrl(Constants.DEFAULT_USER);
        }
        //生成用户token
        String user_token = this.generateToken(hasTaoticketUser);
        //保存用户token到redis中
        this.saveToken(user_token, ttUserVO);
        TokenVO tokenVO = new TokenVO();
        tokenVO.setToken(user_token);
        tokenVO.setExpTime(Constants.Redis_Expire.SESSION_TIMEOUT);
        tokenVO.setGenTime(new Date().getTime());
        return new Object[]{ttUserVO, tokenVO};
    }

    @Override
    public TTUserVO loadCurrentUserByTokenAsTaoticketUserVo(String user_token) throws Exception {
        String tokenUser = null;
        if((tokenUser = (String) redisUtils.get(user_token))==null){
            //抛出异常
            return null;
        }
        return JSONObject.parseObject(tokenUser,TTUserVO.class);
    }

    @Override
    public List<QueryLinkUserVo> findLinkUserByUserId(Long userId) throws Exception {
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        List<TaoticketLinkUser> taoticketLinkUsers = restTaoticketLinkUserClient.getTaoticketLinkUserListByMap(params);
        List<QueryLinkUserVo> linkUserVos = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(taoticketLinkUsers)) {
            //组装数据
            for (TaoticketLinkUser taoticketLinkUser : taoticketLinkUsers) {
                QueryLinkUserVo queryLinkUserVo = new QueryLinkUserVo();
                BeanUtils.copyProperties(taoticketLinkUser,queryLinkUserVo);
                linkUserVos.add(queryLinkUserVo);
            }
            return linkUserVos;
        }
        return null;
    }

    /*
    保存用户token
     */
    private void saveToken(String user_token, TTUserVO ttUserVO) {
        String tokenKey = Constants.USER_TOKEN_PREFIX + ttUserVO.getUserId();

        //检查是否已经登录，如果还在登录有效区内，就需要删除原来的登录信息
        if (redisUtils.get(tokenKey) != null) {
            //代表原来用户已经登录，删除原来登录信息
            redisUtils.delete(tokenKey);
        }
        //如果还没登录，缓存用户token,Constants.Redis_Expire.SESSION_TIMEOUT代表该token的有效期
        redisUtils.set(tokenKey, Constants.Redis_Expire.SESSION_TIMEOUT, user_token);
        //缓存用户详细信息
        redisUtils.set(user_token, Constants.Redis_Expire.SESSION_TIMEOUT, JSON.toJSONString(ttUserVO));
    }

    private String generateToken(TaoticketUser hasTaoticketUser) throws Exception {
        return restTaoticketUserClient.generateToken(hasTaoticketUser);
    }
}
